﻿using System;
using System.Text;
using System.Xml.Linq;

namespace SPQueryToSql.ApplicationObjects.CAML
{
    internal class QueryOptions
    {
        public ViewAttributes ViewAttributes;
        public RowLimit RowLimit;
        public string OptimizeFor;

        public QueryOptions(XContainer element)
        {
            var el1 = element.Element(SPQueryToSql.CAML.ViewAttributes);
            ViewAttributes = el1 != null
                                 ? new ViewAttributes(el1)
                                 : null;
            var el2 = element.Element(SPQueryToSql.CAML.OptimizeFor);
            OptimizeFor = el2 != null
                              ? el2.Value
                              : string.Empty;
            var el3 = element.Element(SPQueryToSql.CAML.RowLimit);
            RowLimit = el3 != null
                              ? new RowLimit(el3)
                              : null;
        }

        public override string ToString()
        {
            return ToString(0);
        }

        public string ToString(int tabQnt)
        {
            var sb = new StringBuilder();
            const string tab = @"    ";
            sb.Append("<QueryOptions>");
            sb.Append(Environment.NewLine);
            sb.Append(ViewAttributes.ToString(1));
            sb.Append(RowLimit.ToString(1));
            if (!string.IsNullOrEmpty(OptimizeFor))
            {
                for (var i = 0; i < tabQnt; i++) sb.Append(tab);
                sb.AppendFormat("<OptimizeFor>{0}</OptimizeFor>", OptimizeFor);
            }
            sb.Append(Environment.NewLine);
            sb.Append("</QueryOptions>");
            return sb.ToString();
        }
    }
}
